package com.duyi.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;

/**
 * 文件下载
 */
@Controller
public class DownloadController {

    @RequestMapping("/fd")
    public ResponseEntity<byte[]> myDownload() throws IOException {

        // 服务器提供的下载文件
        File downloadFile = new File("E:/test/elastic-job-lite-starter-1.0.jar");

        // 用户浏览器下载文件，显示的名字
        String filename = "文件下载dodo.txt";

        HttpHeaders httpHeaders = new HttpHeaders();
        // 二进制 字节流
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 解决中文的文件名
        filename = new String(filename.getBytes("utf-8"), "iso-8859-1");

        httpHeaders.setContentDispositionFormData("attachment", filename);

        ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(
                FileUtils.readFileToByteArray(downloadFile),
                httpHeaders,
                HttpStatus.CREATED
        );

        return result;

    }
}
